package com.cloudfun.campusshare.common.security;


import com.cloudfun.campusshare.common.constant.RoleType;

/**
 * Created by Huqin on 2019/12/23
 */
public class AuthenticationHolder {

    private static final ThreadLocal<AppAuthentication> APP_AUTH_HOLDER = new ThreadLocal<>();
    private static final ThreadLocal<UserAuthentication> USER_AUTH_HOLDER = new ThreadLocal<>();

    public static void setAppAuth(AppAuthentication authentication) {
        APP_AUTH_HOLDER.set(authentication);
    }

    public static AppAuthentication getAppAuth() {
        return APP_AUTH_HOLDER.get();
    }

    public static void setUserAuth(UserAuthentication authentication) {
        USER_AUTH_HOLDER.set(authentication);
    }

    public static UserAuthentication getUserAuth() {
        return USER_AUTH_HOLDER.get();
    }

    public static void clear() {
        APP_AUTH_HOLDER.remove();
        USER_AUTH_HOLDER.remove();
    }

    public static String getUserId() {
        AppAuthentication appAuthentication = APP_AUTH_HOLDER.get();
        if (null != appAuthentication) {
            return appAuthentication.getUserId();
        }
        if (null != USER_AUTH_HOLDER.get()) {
            return USER_AUTH_HOLDER.get().getUserId();
        }
        return null;
    }

    public static boolean isAdmin() {
        if (null == getUserAuth()) {
            return false;
        }
        return getUserAuth().getRoleTypes().contains(RoleType.ADMIN.toString());
    }

    public static boolean isFinancialInstitutions() {
        if (null == getUserAuth()) {
            return false;
        }
        return getUserAuth().getRoleTypes().contains(RoleType.FINANCIAL_INSTITUTIONS.name());
    }

    public static boolean isMerchant() {
        if (null == getUserAuth()) {
            return false;
        }
        return getUserAuth().getRoleTypes().contains(RoleType.OPERATIONAL_MERCHANT.name()) || getUserAuth().getRoleTypes().contains(RoleType.PLATFORM_MERCHANT.name());
    }

    public static boolean isReplenish() {
        if (null == getUserAuth()) {
            return false;
        }
        return getUserAuth().getRoleTypes().contains(RoleType.REPLENISH.name());
    }

    public static boolean isCustomer() {
        if (null == getUserAuth()) {
            return false;
        }
        return getUserAuth().getRoleTypes().contains(RoleType.CUSTOMER.name());
    }


    public static boolean isAgent() {
        if (null == getUserAuth()) {
            return false;
        }
        return getUserAuth().getRoleTypes().contains(RoleType.AGENT.name());
    }

}
